package com.xindacloud.sms.adapter.service.business.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xindacloud.sms.adapter.dao.SmsPricingMapper;
import com.xindacloud.sms.adapter.entity.SmsPricing;
import com.xindacloud.sms.adapter.exception.ServiceException;
import com.xindacloud.sms.adapter.service.business.ISmsPricingService;
import com.xindacloud.sms.adapter.utils.UnionResultHelp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Optional;


@Slf4j
@Service
public class SmsPricingServiceImpl extends ServiceImpl<SmsPricingMapper, SmsPricing> implements ISmsPricingService {

    @Override
    public List<SmsPricing> queryPreferentialPriceOrderByAsc(String countryCode, String countryPrefix) {

        List<SmsPricing> pricingList = lambdaQuery()
                .eq(SmsPricing::getCountryCode, countryCode)
                .eq(SmsPricing::getPrefix, countryPrefix)
                .eq(SmsPricing::getType, "mobile")
                .orderByAsc(SmsPricing::getCostPrice)
                .list();

        Optional.of(pricingList)
                .filter(CollectionUtils::isNotEmpty)
                .orElseThrow(() -> new ServiceException("号码前缀无效：" + countryCode + "无效", UnionResultHelp.StatusEnum.ParamsFail.code()));
        return pricingList;
    }

    @Override
    public Boolean saveBatchPricing(Collection<SmsPricing> smsPricingList) {

        Optional.of(smsPricingList)
                .filter(CollectionUtils::isNotEmpty)
                .orElseThrow(() -> new ServiceException("同步平台价格为空", UnionResultHelp.StatusEnum.InnerError.code()));
        return saveBatch(smsPricingList);
    }

    @Override
    public List<SmsPricing> querySmsPricingListByAgentId(String agentId) {
        return lambdaQuery()
                .eq(SmsPricing::getAgentId, agentId)
                .list();
    }

    @Override
    public Boolean deleteSmsPricingListByAgentId(String agentId) {
        Wrapper<SmsPricing> delWrapper = new QueryWrapper<SmsPricing>()
                .eq("agent_id", agentId);
        return remove(delWrapper);
    }

    @Override
    public List<SmsPricing> queryPricingGroupByCountryCodeAndNetworkCode() {
        return lambdaQuery()
                .groupBy(SmsPricing::getCountryCode, SmsPricing::getNetworkCode)
                .list();

    }
}
